package random

import (
	"context"
	"gitee.com/vrv_media/go-micro-framework/registry"
	"gitee.com/vrv_media/go-micro-framework/registry/balance"
	"math/rand"
)

// 随机的负载均衡算法

type RandomBalancer struct {
}

func NewRandomBalancer() registry.Balancer {
	return &RandomBalancer{}
}

func (b RandomBalancer) Pick(ctx context.Context, nodes []registry.Node) (selected registry.Node, err error) {
	if len(nodes) == 0 {
		return nil, balance.NoNodeError
	}
	if len(nodes) == 1 {
		return nodes[0], nil
	}
	index := rand.Intn(len(nodes))
	return nodes[index], nil
}
